"""
@version:  python3.9
@project:  appium
@file:    Log.py
@date:   2022/05/22 10:00
@Author: jia
@Desc:  公共日志配置
loggers：记录器，提供应用程序代码能直接使用的接口；
handlers：处理器，将记录器产生的日志发送至目的地；
filters：过滤器，提供更好的粒度控制，决定哪些日志会被输出；
formatters：格式化器，设置日志内容的组成结构和消息字段。
"""

import os
import logging.config
import time


def log_execute(loggers):

    """
    配置日志
    :param loggers:记录器，提供应用程序代码能直接使用的接口如“debug_logger”

    """

    # 将当前时间格式化
    local = time.localtime()
    now_time = time.strftime('%Y_%m_%d_%H_%M@', local)

    # 拼接日志保存路径
    base_dir = os.getcwd()
    root_path = base_dir[:base_dir.find("appium\\") + len("appium\\")]
    log_dir = os.path.join(root_path + 'Log/').replace("\\", '/')
    debug_log = os.path.join(log_dir + now_time+'debug.log').replace("\\", '/')
    # email_log = os.path.join(log_dir + now_time+'email.log').replace("\\", '/')
    # db_log = os.path.join(log_dir + now_time+'db.log').replace("\\", '/')
    print('日志路径:', debug_log)

    """
    目录为空时创建目录
    """
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)

    """
    配置参数
    version:表示版本，必选，从1开始的整数
    disable_existing_loggers: False 启动默认配置中的所有记录器,True 禁用
    formatters: 对日志输出的信息进行格式化
    handlers: 选择日志输出的地方如：控制台，文件 ，邮件发送
    propagate (可选)为布尔值用于控制是否向上遍历父辈日志打印器，True，向上遍历，否则不向上遍历。
    loggers:包含多个logger,提供日志记录的方法，一个logger可以添加多个handler
    level:从低到高，debug>info>warning>error>critical 若设置了info级别，debug级别将不被handle处理
    """
    log_conf = {
        "version": 1,
        "disable_existing_loggers": False,
        "formatters": {
            "simple": {
                'format': '%(asctime)s [%(filename)s:%(lineno)d] [%(levelname)s]- %(message)s'
            },
            'standard': {
                'format': '%(asctime)s [%(threadName)s:%(thread)d][%(filename)s:%(lineno)d][%(levelname)s]-%(message)s'
            },
        },
        "handlers": {
            "console": {
                "class": "logging.StreamHandler",
                "level": "DEBUG",
                "formatter": "simple",
                "stream": "ext://sys.stdout"
            },
            # "email": {
            #     "class": "logging.handlers.RotatingFileHandler",
            #     "level": "DEBUG",
            #     "formatter": "simple",
            #     "filename": email_log,
            #     'mode': 'w+',
            #     "maxBytes": 1024 * 1024 * 10,  # 10 MB
            #     "backupCount": 5,
            #     "encoding": "utf8"
            # },
            # "db": {
            #     "class": "logging.handlers.RotatingFileHandler",
            #     "level": "DEBUG",
            #     "formatter": "simple",
            #     "filename": db_log,
            #     'mode': 'w+',
            #     "maxBytes": 1024 * 1024 * 10,  # 10 MB
            #     "backupCount": 5,
            #     "encoding": "utf8"
            # },
            "file": {
                "class": "logging.handlers.RotatingFileHandler",
                "level": "DEBUG",
                "formatter": "simple",
                "filename": debug_log,
                'mode': 'w+',
                "maxBytes": 1024 * 1024 * 10,  # 10 MB
                "backupCount": 5,
                "encoding": "utf-8"
            }
        },
        "loggers": {
            "console_logger": {
                "level": "DEBUG",
                "handlers": ["console"],
                "propagate": "no"
            },
            # "email_logger": {
            #     "level": "DEBUG",
            #     "handlers": ["console", "email"],
            #     "propagate": "no"
            # },
            # "db_logger": {
            #     "level": "DEBUG",
            #     "handlers": ["console", "db"],
            #     "propagate": "no"
            # },
            "info_logger": {
                "level": "INFO",
                "handlers": ["console", "file"],
                "propagate": "no"
            }
        }
    }

    # 读取字典格式config对logging进行配置
    logging.config.dictConfig(log_conf)
    # 初始化logger
    logger = logging.getLogger(loggers)

    return logger

